package com.shoppingmall.controller.portal;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.demo.trade.config.Configs;
import com.google.common.collect.Maps;
import com.shoppingmall.common.Constant;
import com.shoppingmall.common.ServletResponse;
import com.shoppingmall.pojo.User;
import com.shoppingmall.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by
 *
 * @author touni
 * @date 2019/3/25
 * @time 12:39
 */


@RestController
@RequestMapping("/order")
public class OrderController {


    private static final Logger log = LoggerFactory.getLogger(OrderController.class);

    /**
     * 存储用户的session的名称
     */
    @Value("${USER_SESSION}")
    private String userSessoin;



    @Autowired
    private OrderService orderService;

    /**
     * 用来进行支付的   生成二维码    二维码暂时存储到本地
     * @param session
     * @param orderId
     * @return
     */
    @RequestMapping("/pay")
    public ServletResponse alipayOrder(HttpSession session,Long orderId){
        User userFromSession = (User)session.getAttribute(userSessoin);
        if (null == userFromSession){
            return ServletResponse.createByErrorMessage("您还未登录呢，请您先登录");
        }
        return orderService.alipayOrder(userFromSession.getId(),orderId);

    }


    /**
     * 处理支付宝支付中的回调  由支付宝端进行调用
     * @param request
     * @return
     */
    @RequestMapping("/alipay_call_back")
    public Object alipayCallBack(HttpServletRequest request){
        //获取支付宝post请求过来的参数
        HashMap<String, String > params = Maps.newHashMap();
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (Iterator iterator = parameterMap.keySet().iterator();iterator.hasNext();){
            String name = (String)iterator.next();
            String[] value = parameterMap.get(name);
            String valueStr = "";
            for (int i = 0; i < value.length; i++) {
                valueStr = (i == value.length -1)?valueStr+value[i]:valueStr+value[i]+",";
            }
            params.put(name,valueStr);
        }
        log.info("支付宝回调，sign:{},trade_status:{},参数:{}",params.get("sign"),params.get("trade_status"),params.toString());

        try {
            boolean flag = AlipaySignature.rsaCheckV1(params, Configs.getAlipayPublicKey(), "utf-8", Configs.getSignType());
            if (!flag){
                return ServletResponse.createBySuccessMessage("请求不合法！！！！");
            }

        } catch (AlipayApiException e) {

            e.printStackTrace();
            log.info("支付宝验证回调失败",e);
        }
        //对参数进行处理  更新数据库状态等操作
        ServletResponse orderPayBack = orderService.alipayCallBack(params);
        if (!orderPayBack.isSuccess()){
            return Constant.AlipayCallback.RESPONSE_FAILED;
        }
        return Constant.AlipayCallback.RESPONSE_SUCCESS;

    }

    /**
     * 根据用户名和订单号查询订单的状态
     * @param session
     * @param orderId
     * @return
     */
    @RequestMapping("/query_order_pay_status")
    public ServletResponse queryOrderPayStatus(HttpSession session,Long orderId){
        User userFromSession = (User)session.getAttribute(userSessoin);
        if (null == userFromSession){
            return ServletResponse.createByErrorMessage("您还未登录呢，请您先登录");
        }

        return orderService.queryOrderPayStatus(userFromSession.getId(),orderId);


    }

    //以上全为支付相关的

    /**
     * 创建订单
     * @param session
     * @param shippingId
     * @return
     */
    @RequestMapping("/create")
    public ServletResponse createOrder(HttpSession session,Integer shippingId){
        User userFromSession = (User)session.getAttribute(userSessoin);
        if (null == userFromSession){
            return ServletResponse.createByErrorMessage("您还没有登录，请先登录");
        }
        if (null == shippingId){
            return ServletResponse.createByErrorMessage("收货地址不能为空");
        }
        return  orderService.createOrder(userFromSession.getId(),shippingId);
    }

    /**
     * 根据用户ID 查询所有的订单信息  没弄懂为何需要这个方法
     * @param session
     * @return
     */
    @RequestMapping("/get_order_cart_product")
    public ServletResponse getAllOrderProduct(HttpSession session){
        User userFromSession = (User)session.getAttribute(userSessoin);
        if (null == userFromSession){
            return ServletResponse.createByErrorMessage("您还没有登录，请先登录");
        }
        return orderService.getAllOrderProduct(userFromSession.getId());
    }

    /**
     *根据用户ID查询所有的订单
     * @param pageSize
     * @param pageNum
     * @param session
     * @return
     */
    @RequestMapping("/list")
    public ServletResponse listAllOrder(@RequestParam(defaultValue = "10")Integer pageSize,
                                        @RequestParam(defaultValue = "1")Integer pageNum,
                                        HttpSession session){
        User userFromSession = (User)session.getAttribute(userSessoin);
        if (null == userFromSession){
            return ServletResponse.createByErrorMessage("您还没有登录呢！！！");
        }

        return orderService.listAllOrder(userFromSession.getId(),pageNum,pageSize);
    }

    /**
     * 根据订单号 查看订单的详情
     * @param session
     * @param orderNo
     * @return
     */
    @RequestMapping("/detail")
    public ServletResponse queryOrderDetail(HttpSession session,Long orderNo){
        User userFromSession = (User)session.getAttribute(userSessoin);
        if (null == userFromSession){
            return ServletResponse.createByErrorMessage("请您先登录");
        }
        if (null == orderNo){
            return ServletResponse.createByErrorMessage("参数不合法");
        }
        return orderService.queryOrderDetail(userFromSession.getId(),orderNo);
    }


    @RequestMapping("/cancel")
    public ServletResponse cancelOrder(HttpSession session,
                                       Long orderNo){
        User userFromSession = (User)session.getAttribute(userSessoin);
        if (null == userFromSession){
            return ServletResponse.createByErrorMessage("用户未登录");
        }
        if (null == orderNo){
            return ServletResponse.createByErrorMessage("参数不合法");
        }
        return orderService.cancelOrder(userFromSession.getId(),orderNo);

    }




















}
